package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.ScheduleMapper;
import com.zhentao.mapper.SourceMapper;
import com.zhentao.pojo.Schedule;
import com.zhentao.pojo.Source;
import com.zhentao.service.ScheduleService;
import com.zhentao.vo.ScheduleFormDTO;
import com.zhentao.vo.ScheduleQueryDTO;
import com.zhentao.vo.SourceFormDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Lenovo
* @description 针对表【schedule(排班主表)】的数据库操作Service实现
* @createDate 2025-08-07 15:13:30
*/
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule>
    implements ScheduleService{

    @Autowired
    private SourceMapper sourceMapper;


    @Override
    public IPage<Schedule> getSchedulePage(IPage<Schedule> page, ScheduleQueryDTO queryDTO) {
        LambdaQueryWrapper<Schedule> wrapper = new LambdaQueryWrapper<>();

        // 条件：医生ID
        if (queryDTO.getDoctorId() != null) {
            wrapper.eq(Schedule::getDoctorId, queryDTO.getDoctorId());
        }
        // 条件：科室ID
        if (queryDTO.getDeptId() != null) {
            wrapper.eq(Schedule::getDeptId, queryDTO.getDeptId());
        }
        // 条件：日期范围
        if (queryDTO.getStartDate() != null && queryDTO.getEndDate() != null) {
            wrapper.between(Schedule::getScheduleDate, queryDTO.getStartDate(), queryDTO.getEndDate());
        }
        // 条件：排班状态
        if (queryDTO.getScheduleStatus() != null) {
            wrapper.eq(Schedule::getScheduleStatus, queryDTO.getScheduleStatus());
        }

        // 执行分页查询
        IPage<Schedule> schedulePage = baseMapper.selectPage(page, wrapper);

        // 关联查询号源信息（示例：简单查询，实际可优化为批量查询）
        schedulePage.getRecords().forEach(schedule -> {
            LambdaQueryWrapper<Source> sourceWrapper = new LambdaQueryWrapper<>();
            sourceWrapper.eq(Source::getScheduleId, schedule.getScheduleId());
            List<Source> sources = sourceMapper.selectList(sourceWrapper);
            // 可将号源信息存入 Schedule 的扩展字段，或返回 VO
        });

        return schedulePage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveSchedule(ScheduleFormDTO formDTO) {
        // 1. 保存排班
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(formDTO, schedule);
        baseMapper.insert(schedule);

        // 2. 生成号源（根据 formDTO.sources 或默认规则）
        List<Source> sources = formDTO.getSources().stream().map(sourceForm -> {
            Source source = new Source();
            BeanUtils.copyProperties(sourceForm, source);
            source.setScheduleId(schedule.getScheduleId()); // 关联排班ID
            source.setRemainNum(formDTO.getTotalNum());      // 初始剩余号数=总号数
            source.setSourceStatus(1);                       // 默认可预约
            return source;
        }).collect(Collectors.toList());

        // 批量插入号源
        sourceMapper.insertBatchSomeColumn(sources); // 使用 SourceMapper 批量插入号源

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSchedule(ScheduleFormDTO formDTO) {
        // 1. 更新排班信息
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(formDTO, schedule);
        baseMapper.updateById(schedule);



        // 2. 处理号源（新增/修改/删除）
        if (formDTO.getSources() != null && !formDTO.getSources().isEmpty()) {
            formDTO.getSources().forEach(sourceForm -> {
                Source source = new Source();
                BeanUtils.copyProperties(sourceForm, source);
                source.setScheduleId(schedule.getScheduleId());

                if (source.getSourceId() == null) {
                    // 新增号源
                    sourceMapper.insert(source);
                } else {
                    // 修改号源
                    sourceMapper.updateById(source);
                }
            });
        }

        return true;
    }

    @Override
    public boolean removeSchedule(Long scheduleId) {
        // 1. 删除号源（根据排班ID）
        LambdaQueryWrapper<Source> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Source::getScheduleId, scheduleId);
        sourceMapper.delete(wrapper);

        // 2. 删除排班
        return baseMapper.deleteById(scheduleId) > 0;
    }

    @Override
    public boolean updateSource(SourceFormDTO formDTO) {
        Source source = new Source();
        BeanUtils.copyProperties(formDTO, source);
        return sourceMapper.updateById(source) > 0;
    }
}




